const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const CleanWebpackPlugin = require('clean-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin') // 复制

const path = require('path')
const fs = require('fs')
const Conf = require('./config/config.js')
console.log(process.env.NODE_ENV)
process.env.NODE_ENV = process.env.NODE_ENV || 'development'

function walk(dir, rootpath, isSingle) {
  isSingle = isSingle || false
  var children = []
  fs.readdirSync(dir).forEach(function (filename) {
    // 判断是否单页应用（单页应用暂时只做一级目录）
    var newpath = path.join(dir, filename)
    var stat = fs.statSync(newpath)
    if (stat && stat.isDirectory()) {

      children = children.concat(walk(newpath, filename, isSingle))
    } else {
      if (isSingle) {
        if (/main\.js$/.test(filename)) {
          if (rootpath) {
            children.push(rootpath + '/' + filename)
          } else {
            children.push(filename)
          }
        }
      } else {
        if (/\.html$/.test(filename)) {
          if (rootpath) {
            children.push(rootpath + '/' + filename)
          } else {
            children.push(filename)
          }
        }
      }
    }
  })
  return children
}



let entry = {}

/*let data = walk(Conf.normalRoot) // 这个是正常的目录和路径（只获取html）

let as = data.map(item => {
    // 去除根目录
    entry['__normalPages__' + item.replace('.html', '')] = path.join(Conf.normalRoot, item)
    return new HtmlWebpackPlugin({
        filename: 'normalPages/' + item,
        inject: false,
        template: path.join(Conf.normalRoot, item)
    })
})*/

let singlets = path.join(Conf.singleRoot, 'pages')
let data2 = walk(singlets, '', true) // 这个是单页面的应用

let bs = data2.map(item => {
  let res = item.replace('/main.js', '')
  entry[res] = path.join(singlets, item)
  return new HtmlWebpackPlugin({
    title: 'myt',
    filename: res + '.html',
    chunks: [res, 'common'],
    template: path.join(singlets, res, 'index.ejs')
  })
})


let plugins = bs


module.exports = {
  mode: process.env.NODE_ENV,
  entry: entry,
  output: {
    path: __dirname + '/html/dist/',
    filename: 'js/[name].js',
  },
  module: {
    rules: [{
        test: /\.(js|vue)$/,
        enforce: 'pre',
        exclude: /node_modules/,
        use: {
          loader: 'eslint-loader',
          options: {
            formatter: require('eslint-friendly-formatter')
          }
        }
      },
      {
        test: /\.vue$/,
        use: { loader: 'vue-loader' }
      },
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          "css-loader"
        ]
      },
      {
        test: /\.(png|jpe?g|gif|svg)$/,
        loader: 'url-loader?limit=8192&name=images/[hash:8].[name].[ext]'
      },
      {
        test: /\.js$/,
        use: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(woff2?|svg|eot|ttf|otf)(\?.*)?$/,
        use: {
          loader: 'url-loader',
          query: {
            limit: 10000,
            name: 'fonts/[name]--[folder].[ext]'
          }
        }
      }
    ]
  },
  resolve: {
    alias: {
      'vue': 'vue/dist/vue.js',
      '#': __dirname,
      '@': path.join(__dirname, 'html/pack'),
    }
  },
  /*    devServer: {
        hot: true
      },*/
  plugins: [
    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.optimize.SplitChunksPlugin({
      chunks: "all",
      minSize: 30000,
      minChunks: 2,
      maxAsyncRequests: 5,
      maxInitialRequests: 3,
      default: false,
      cacheGroups: {
        common: {
          name: "common",
          chunks: "initial",
          minChunks: 2
        }
      }
    }),
    new CleanWebpackPlugin(
      ['html/dist'], //匹配删除的文件
      {
        root: __dirname, //根目录
        verbose: true, //开启在控制台输出信息
        dry: false //启用删除文件
      }
    ),
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "css/[id].css"
    }),
    ...plugins
  ],
  target: 'electron-renderer'
}